package com.hlk.im.gateway.tcp;

import io.netty.channel.socket.SocketChannel;

import java.util.concurrent.ConcurrentHashMap;

public class NettyChannelManager {

    public NettyChannelManager(){

    }
    /**
     * 单例内部类
     */
    static class Singleton {
        public static NettyChannelManager instance= new NettyChannelManager();
    }

    /**
     * 获取单例
     * @return
     */
    public static NettyChannelManager getInstance() {
        return Singleton.instance;
    }

    /**
     * 存储所有的客户连接
     */
    private ConcurrentHashMap<String, SocketChannel> channels = new ConcurrentHashMap<>();
    /**
     * 保存客户端的一个id
     */
    private ConcurrentHashMap<String,String> channelIds = new ConcurrentHashMap<>();

    /**
     * 放入一个客户端链接的缓存
     * @param userId
     * @param socketChannel
     */
    public void addChannel(String userId,SocketChannel socketChannel){
        channelIds.put(socketChannel.remoteAddress().getHostName(), userId);
        channels.put(userId,socketChannel);
    }

    /**
     * 判断认证过的客户端是否又链接存在
     * @param userId
     * @return
     */
    public Boolean existChannel(String userId){
        return channels.containsKey(userId);
    }

    /**
     * 根据用户id获取对应的ke客户端连接
     @param userId
     * @return
     */
    public SocketChannel getChannel(String userId){
        return channels.get(userId);
    }

    /**
     * 删除一个客户端的连接
     * @param channel
     */
    public void removeChannel(SocketChannel channel){
        String userId = channelIds.get(channel.remoteAddress().getHostName());
        channelIds.remove(channel.remoteAddress().getHostName());
        channels.remove(userId);
    }
}
